5.4.1 ジェネリクス
ジェネリック型は、どのデータ型を使っても構わないことを示すためのもの
typing.TypeVar
def reverse(coll: list[T]) -> list[T]:
T型の要素のリストを受け取り、T型のリストを返す
T型は一致(別々にはならない)
typing.Generic
グラフの例:https://github.com/pviafore/RobustPython/blob/dafb95d801dff2c8ff7856ba46d3c052d54e0033/code_examples/chapter5/graph.py
class Graph(Generic[Node, Edge]):
NewType(typing)を使って、Restaurant型(strのサブタイプ)
あらゆる要素型のグラフを定義でき、かつそれらの型チェックを成功させられる。
その他の用途:APIのエラー処理の単純化
https://github.com/pviafore/RobustPython/blob/dafb95d801dff2c8ff7856ba46d3c052d54e0033/code_examples/chapter5/generic.py
APIResponse = Union[T, APIErrorResponse]
APIResponse[NutritionInfo](型変数Tに実際の型を代入した)
IMO:型定義の重複を解消する使い方ができる模様